package com.bdit.ydcb.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.service.LocationService;
import com.bdit.ydcb.MyApplication;
import com.bdit.ydcb.R;
import com.bdit.ydcb.callback.DialogCallback;
import com.bdit.ydcb.callback.JsonCallback;
import com.bdit.ydcb.model.ServerResponse;
import com.bdit.ydcb.model.WaterUser;
import com.bdit.ydcb.utils.Urls;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.BodyRequest;
import com.lzy.okgo.request.base.Request;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.vise.log.ViseLog;

import java.io.File;
import java.util.List;


public class WaterUserDetailActivity extends Activity implements  View.OnClickListener{
    private static final String TAG = "WaterUserDetailActivity";
    private LinearLayout top_bar_linear_back;
    private TextView top_bar_title;
    private ImageView imageView;
    private TextView last_num;
    private TextView last_date;
    private EditText current_num;
    private TextView user_no;
    private TextView meter_no;
    private TextView phone;
    private TextView address;
    private WaterUser c_wu;
    private Button commit_button;
    private Button location_button;
    private String imageUrl="";
    private double lat;
    private double lng;
    private LocationService locationService;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_water_user_detail);
        findView();
        initData();

    }
    private void findView(){
        top_bar_linear_back = (LinearLayout)this.findViewById(R.id.top_bar_linear_back);
        top_bar_linear_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                WaterUserDetailActivity.this.finish();
            }
        });
        top_bar_title = (TextView) this.findViewById(R.id.top_bar_title);
        imageView = (ImageView) this.findViewById(R.id.cb_imageview);
        imageView.setOnClickListener(this);
        last_num = (TextView) findViewById(R.id.last_num);
        last_date = (TextView) findViewById(R.id.last_date);
        current_num = (EditText) findViewById(R.id.current_num);
        current_num.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        user_no = (TextView) findViewById(R.id.user_no);
        meter_no = (TextView) findViewById(R.id.meter_no);
        phone = (TextView) findViewById(R.id.phone);
        address = (TextView) findViewById(R.id.address);
        commit_button = (Button) findViewById(R.id.cb_commit);
        location_button = (Button) findViewById(R.id.location_commit);
        commit_button.setOnClickListener(this);
        location_button.setOnClickListener(this);
    }
    private void initData(){
        Intent intent = getIntent();
        c_wu = (WaterUser) intent.getSerializableExtra("waterUser");
        top_bar_title.setText(c_wu.getUserName());
        if(c_wu.getLastNum()!=null){
            last_num.setText(c_wu.getLastNum().toString());
        }
        if (c_wu.getCurrentNum() != null && c_wu.getCurrentNum() > 0.0) {
            current_num.setText(c_wu.getCurrentNum().toString());
        }
        if (c_wu.getPic() != null && !"".equals(c_wu.getPic())) {
            ViewGroup.LayoutParams para = imageView.getLayoutParams();
            para.height = 400;
            para.width  = 800;
            imageView.setLayoutParams(para);
            Glide.with(WaterUserDetailActivity.this)
                    .load(Urls.ORIGINAL_SERVER+c_wu.getPic())
                    .override(800,400)
                    .placeholder(R.drawable.loading3)
                    .thumbnail(0.5f)
                    .error(R.drawable.load_error)
                    .into(imageView);
        }
        last_date.setText(c_wu.getLastDate());
        user_no.setText(c_wu.getUserNo());
        meter_no.setText(c_wu.getMeterNo());
        phone.setText(c_wu.getPhone());
        address.setText(c_wu.getAddress());
        commit_button.setText("定位中....");
        commit_button.setEnabled(false);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cb_imageview:
                AndroidImagePicker.getInstance().pickSingle(WaterUserDetailActivity.this, true, new AndroidImagePicker.OnImagePickCompleteListener() {
                    @Override
                    public void onImagePickComplete(List<ImageItem> items) {
                        if(items != null && items.size() > 0){
                            Log.i(TAG,"=====选择了："+items.get(0).path);
                            imageUrl = items.get(0).path;
                            //presenter.onPresentImage(imageView,items.get(0).path,1000);
                            Glide.with(WaterUserDetailActivity.this)
                                    .load(imageUrl)
                                    .override(800,400)
                                    .error(R.drawable.load_error)
                                    .into(imageView);

                        }
                    }
                });
                break;
            case R.id.cb_commit:
                commit_cb();
                break;
            case R.id.location_commit:
                location_button.setText("定位中....");
                location_button.setEnabled(false);
                locationService.start();// 定位SDK
                break;
        }

    }
    private  void commit_cb(){
        if ("".equals(imageUrl)&&(c_wu.getPic()==null||"".equals(c_wu.getPic()))) {
            Toast.makeText(WaterUserDetailActivity.this,"请选择水表图片",Toast.LENGTH_SHORT).show();
            return;
        }
        double lastNum = c_wu.getLastNum();
        if (Double.valueOf(current_num.getText().toString()) < c_wu.getLastNum()) {
            Toast.makeText(WaterUserDetailActivity.this,"本次读数不能小于上次读数",Toast.LENGTH_SHORT).show();
            return;
        }
        BodyRequest bodyRequest= OkGo.<ServerResponse>post(Urls.POST_CB_URL)
                .tag(this)
                .params("id",c_wu.getId())
                .params("currentNum",current_num.getText().toString())
                .params("lat",lat)
                .params("lng",lng);

        if(!"".equals(imageUrl)){
            File file = new File(imageUrl);
            bodyRequest.params("file",file);
        }
       bodyRequest.isMultipart(true).execute(new DialogCallback<ServerResponse>(this) {
            @Override
            public void onStart(Request<ServerResponse, ? extends Request> request) {
                setDialogMessage("提交中...");
                super.onStart(request);
            }

            @Override
            public void onSuccess(Response<ServerResponse> response) {
                ServerResponse result = response.body();
                if(result.success){
                    WaterUserDetailActivity.this.finish();
                }
            }
        });


    }
    public void changeButton() {

        try {
            if (address != null){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        address.post(new Runnable() {
                            @Override
                            public void run() {
                                commit_button.setText("确定");
                                commit_button.setEnabled(true);
                                location_button.setText("上报位置");
                                location_button.setEnabled(true);
                            }
                        });

                    }
                }).start();
            }
            //LocationResult.setText(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // -----------location config ------------
        locationService =((MyApplication)getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }
    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }
    public void commitLocation(BDLocation location){
        OkGo.<ServerResponse>post(Urls.POST_WATER_LOCATION)
                .tag(this)
                .params("userNo",c_wu.getUserNo())
                .params("lat",lat)
                .params("lng",lng)
                .params("locType",location.getLocType())
                .params("direction",location.getDirection())
                .params("userIndoorState",location.getUserIndoorState())
                .params("satelliteNumber",location.getSatelliteNumber())
                .params("speed",location.getSpeed())
                .params("gpsAccuracyStatus",location.getGpsAccuracyStatus()).execute(
                new JsonCallback<ServerResponse>() {

                    @Override
                    public void onSuccess(Response<ServerResponse> response) {
                        ServerResponse result = response.body();
                        ViseLog.d(result);
                    }
                }
        );
    }
    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            ViseLog.d(location);
            StringBuffer sb = new StringBuffer(256);
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                lat = location.getLatitude();
                lng = location.getLongitude();

                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */

                sb.append(location.getTime());
                sb.append("\n定位类型 : ");// 定位类型
                sb.append(location.getLocType());

                sb.append("\n室内外: ");// *****返回用户室内外判断结果*****
                sb.append(location.getUserIndoorState());
                sb.append("\n方向: ");
                sb.append(location.getDirection());// 方向
                sb.append("\nlocationdescribe: ");
                changeButton();
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 速度 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());// 卫星数目
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 海拔高度 单位：米
                    sb.append("\ngps status : ");
                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    if (location.hasAltitude()) {// *****如果有海拔高度*****
                        sb.append("\nheight : ");
                        sb.append(location.getAltitude());// 单位：米
                    }
                    sb.append("\n运营商信息 : ");// 运营商信息
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                }
                commitLocation(location);


            }else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            ViseLog.d(sb.toString());
            //Toast.makeText(WaterUserDetailActivity.this,sb.toString(),Toast.LENGTH_LONG).show();
            locationService.stop();
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    };
}
